<template>
  <div>
    <a-modal  title="服务范围划定" :visible="true" @cancel="closeHandle" width="90%"  @ok="confirmHandle" :confirmLoading="confirmLoading">
      <div class="flex items-center justify-between mb-15">
        <div class=" flex items-center">
          <a-button type="primary" class="btn" @click="isStarDrawingHandle" :disabled="isShowCurrentRang">{{`${isStarDrawing?'关闭':'开启' }钢笔规划`}}</a-button>
          <a-button type="link"  class="text-red-501 cursor-pointer text-14"   @click="clearAllHnalde">清除所有</a-button >
        </div>

        <div class="relative flex items-center">
          <div class="mr-10">
            <a-checkbox v-model="isShowCurrentRang" class="text-blue-501">
              <span class="mr-10 text-blue-501">仅显示当前设置服务范围</span>
            </a-checkbox>
          </div>

          <div class="relative">
            <a-input placeholder="请输入定位位置" class="w-400" v-model="keywords" allow-clear  />
            <div class="w-full absolute top-0 mt-40 ss-serach-box px-10 bg-white" v-if="isShowSearchList&&searchList.length>0">
              <div class="relative py-15 text-12 relative b-line cursor-pointer" v-for="(item, index) in searchList" :key="index" @click="serchItemClickHandle(item)">{{item.name}}{{item.address}}</div>
            </div>
          </div>
        </div>

      </div>


      <div>
        <div id="container2" style="height: 700px"></div>
      </div>

    </a-modal>
  </div>
</template>

<script>

  import _ from  'lodash'
  import { setServiceScopeCoordinates, } from '@/api/store.js'
  let map_del_icon = require('@/assets/map_del.png')
  export default {
    name: 'addServiceScopePop',
    props: {
      id: {
        type: Number,
        default() {
          return 0
        }
      },
      coordinatesArr: { // 服务的点集合
        type: Array,
        default() {
          return []
        }
      },
      color: { // 编辑的颜色
        type: String,
        default () {
          return '#4fa640'
        }
      },
      center: { // 地图的中心
        type: Array,
        default(){
          return []
        }
      },
      nameColor: { // 范围名称
        type: String,
        default () {
          return ''
        }
      },
      city: { // 当前搜索的城市
        type: String,
        default () {
          return ''
        }
      },

      callBack: { // 回调函数
        type: Function,
        default(){
          return ()=>{}
        }
      },

      isShowDefaultRange: { // 是否展示门店中心
        type: Boolean,
        default(){
          return false
        }
      },

      pageList: { // 所有列表数据
        type: Array,
        default(){
          return []
        }
      },
    },
    watch: {
      keywords() {
        this.searchHandle()
      },
      isShowCurrentRang(nVal){ //  是否仅显示当前服务范围
        let allPolygon =  this.map.getAllOverlays('polygon')
        let allText =  this.map.getAllOverlays('text')
        let otherPlygon = allPolygon.filter((x)=> x.getExtData().type == 'other')
        let otherText =  allText.filter((x)=> x.getExtData().type == 'other')

        if (nVal){ //仅显示当前
          this.isStarDrawing = false
          this._overDrawPolygon(true)
          this._polyEditorClose()
          this.map.remove([...this.map.getAllOverlays('marker').filter((x)=>x.getExtData().type !== 'storeCenter')])

          otherPlygon.map((x)=>{ x.hide()})
          otherText.map((x)=>{ x.hide()})
        } else {
          otherPlygon.map((x)=>{ x.show()})
          otherText.map((x)=>{ x.show()})
          this._drawPolygon()
        }
      },
    },
    data(){
      return {
        map: null, // 地图对象
        placeSearch: null, // 搜索对象
        mouseTool: null, // 绘画对象
        isAddIng: false, // 是否在绘制矢量
        isStarDrawing: false, // 是否开始绘画
        keywords: '', // 搜索关键字
        searchList: [], // 搜索出来的数据
        isShowSearchList: false, // 是否显示搜索出来的list
        isShowCurrentRang: false, // 是否仅显示当前设置的范围
        confirmLoading: false, // 页面是否在加载中
      }
    },

    mounted() {
      this.$nextTick(() => {
        this.iniMap()
      })
    },

    methods: {

      /*地图相关s*/
      iniMap() { // 初始化地图
        this.map = new AMap.Map('container2', {
          center: this.center,
          zoom: 12
        })
        if (this.coordinatesArr&&this.coordinatesArr.length> 0) {
          this._polygonSelf() // 绘画当前区域
        }

        this._polygonOther() // 绘制其他区域
        this.isShowDefaultRange&&this.creatStoreCircle() // 绘制门店中心

        this.map.on('click', (event) => {
          this.mapClickHandler(event)
        })

        this.mouseTool = new AMap.MouseTool(this.map)
        AMap.plugin('AMap.PlaceSearch', ()=> {
          this.placeSearch = new AMap.PlaceSearch({
            pageSize: 100,
            city:this.city
          });
        })

        this.mouseTool.on('draw', (event) => {
          this._addPolygonToMap(this.getPathArr(event.obj.getPath()))
        })

        this.polyEditor = new AMap.PolygonEditor(this.map)
        this.polyEditor.on('addnode', (event) => {
          let currentArea = event.target
          this.map.remove([...this.map.getAllOverlays('marker').filter((x)=>x.getExtData().type !== 'storeCenter')])
          this._addDelMarker(this._getTopLnglat(currentArea.getPath()), currentArea, currentArea.getExtData().id) // 添加删除覆盖物
          if (this._isInRingRingIntersectFn(currentArea, '所绘制的区域间不可有交点...')) {
            this.map.remove(this.map.getAllOverlays('text').filter(x=> x.getExtData().id == currentArea.getExtData().id))
            this.map.remove(currentArea)
          }
          console.log(event, '触发事件：增加一个节点时触发此事件')
        })

        this.polyEditor.on('adjust', (event) => {
          let currentArea = event.target
          this.map.remove([...this.map.getAllOverlays('marker').filter((x)=>x.getExtData().type !== 'storeCenter')])
          this._addDelMarker(this._getTopLnglat(currentArea.getPath()), currentArea, currentArea.getExtData().id) // 添加删除覆盖物
          if (this._isInRingRingIntersectFn(currentArea, '所绘制的区域间不可有交点...')) {
            this.map.remove(this.map.getAllOverlays('text').filter(x=> x.getExtData().id == currentArea.getExtData().id))
            this.map.remove(currentArea)
          }
          console.log(event, '触发事件：adjust')
        })

        this.polyEditor.on('removenode', (event) => {
          this._overDrawPolygon(true)
          setTimeout(()=>{
            this._drawPolygon()
          },10)
          console.log('触发事件：移除一个节点时触发此事件')
        })

        this.polyEditor.on('end', (event) => {
          console.log('触发事件： 调用close之后触发该事件，target即为编辑后的覆盖物对象')
        })

      },

      _polyEditorClose() { // 结束编辑矢量
        this.polyEditor && this.polyEditor.close()
        // this.polyEditor && this.polyEditor.clearAdsorbPolygons()
      },

      _polyEditor(polygon) { // 编辑多边形
        this.map.remove([...this.map.getAllOverlays('marker').filter((x)=>x.getExtData().type !== 'storeCenter')])
        this._polyEditorClose()
        this.polyEditor.setTarget(polygon)
        this.polyEditor.open()
        this._addDelMarker(this._getTopLnglat(polygon.getPath()), polygon, polygon.getExtData().id) // 添加删除覆盖物

      },

      _polygonSelf() { // 绘画当前区域
        let paths = this.coordinatesArr
        paths.map((x, i)=>{
          this._addCenterMark(this.$utils.getPointsCenter(x), this.color, this.nameColor, i, 1, 'self') // 设置文案
          new AMap.Polygon({
            map: this.map,
            path:x,
            strokeColor: 'rgba(24,144,255,.01)',
            strokeWeight: 4,
            strokeOpacity: 0.4,
            fillOpacity: 0.6,
            fillColor: this.color,
            zIndex: 50,
            bubble: true,
            extData: {
              id: i,
              type: 'self'
            }
          }).on('click', (e)=>{
            if (this.isShowCurrentRang) return this.$message.error('当前不可编辑')
            this._polyEditor(e.target)
            this._overDrawPolygon(true)
            setTimeout(()=>{
              this._drawPolygon()
            },10)
          })
        })

      },

      _polygonOther(){ // 绘画其他区域
        this.pageList.filter((b)=>  b.id !== this.id ).map((x1, i1) => {
          x1.coordinatesArr.length > 0 && x1.coordinatesArr.map((x2, i2) => {
            this._addCenterMark(this.$utils.getPointsCenter(x2), x1.color, x1.name, -1, 0.5, 'other') // 设置文案
            this.map.add(new AMap.Polygon({
              map: this.map,
              path: x2,
              strokeColor: 'rgba(24,144,255,.01)',
              strokeWeight: 6,
              strokeOpacity: 0.1,
              fillOpacity: 0.2,
              fillColor: x1.color,
              zIndex: 50,
              bubble: true, // 事件冒泡到地图上
              extData: {
                id: i1+'-'+i2,
                type: 'other'
              }
            }))
          })
        })
      },

      creatStoreCircle(){ // 绘制圆
        let e = this.pageList.find((x)=>x.isSystemGenerate)
        let center = this.center // 门店中心
        console.log(center, '开始绘制圆圈')
        let circle = new AMap.Circle({
          center,
          radius: 5000, //半径
          borderWeight: 3,
          strokeColor: e.color,
          strokeWeight: 6,
          strokeOpacity: 0.1,
          fillOpacity: 0.2,
          strokeStyle: 'solid',
          strokeDasharray: [10, 10],
          // 线样式还支持 'dashed'
          fillColor: '#1791fc',
          zIndex: 0,
          bubble: true,
          extData: {
            type: 'storeCenter'
          }
        })

        this.map.add(circle);

        let text = new AMap.Text({
          text: e.name,
          anchor:'center', // 设置文本标记锚点
          style:{
            'padding': '5px 5px',
            'background-color': '#188ffd',
            'border-width': '2px',
            'text-align': 'center',
            'font-size': '16px',
            'color': '#ffffff',
            'border-color': 'rgba(0,0,0,.1)',
            'border-style': 'solid',
            'max-width': '300px',
            'opacity': 1
          },
          position: center,
          extData: {
            type: 'storeCenter'
          }
        });
        text.setMap(this.map);

        let iconMark = new AMap.Marker({
          position: center,
          anchor: 'center',
          size: new AMap.Size(30, 30),
          icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
          offset: new AMap.Pixel(5, -30),
          extData: {
            type: 'storeCenter'
          }
        });

        this.map.add(iconMark)

      },

      clearAllHnalde(){ // 清除所有
        this.$confirm({
          title: '提示',
          content: `清除后当前划定所有范围将被删除，确定清除？`,
          okText: '确定',
          okType: 'danger',
          cancelText: '取消',
          onOk: () => {
            this.polyEditor.close()
            this.map.remove([...this.map.getAllOverlays('marker').filter((x)=>x.getExtData().type !== 'storeCenter'), ...this.map.getAllOverlays('polygon').filter((x)=> x.getExtData().type == 'self'),...this.map.getAllOverlays('text').filter((x)=> x.getExtData().type == 'self')])
          }
        })
      },

      mapClickHandler(event) { // 地图点击事件
        if (this.isAddIng) { // 是否在描绘中
          // 开始绘制就要结束编辑
          this.map.remove([...this.map.getAllOverlays('marker').filter((x)=>x.getExtData().type !== 'storeCenter')])
          this._polyEditorClose()
        } else { // 编辑
          // 移除所有的
        }
      },

      _addCenterMark(center, backgroundColor, text, id, opacity, type){ // 添加中心覆盖物文案
        let textMark = new AMap.Text({
          text,
          anchor:'center', // 设置文本标记锚点
          style:{
            'padding': '5px 5px',
            'background-color': backgroundColor,
            'border-width': '2px',
            'text-align': 'center',
            'font-size': '14px',
            'color': '#ffffff',
            'border-color': 'rgba(0,0,0,.1)',
            'border-style': 'solid',
            'max-width': '300px',
            'opacity': opacity
          },
          position: center,
          extData: {
            id,type
          }
        });
        textMark.setMap(this.map);
      },



      _addPolygonToMap(path) { // 绘制好的图形直接添加到地图上
        this._overDrawPolygon(true) // 结束当前绘画
        let currentArea = new AMap.Polygon({
          path,
          strokeColor: '#FF33FF',
          strokeWeight: 4,
          strokeOpacity: 0.2,
          fillOpacity: 0.4,
          fillColor: this.color,
          zIndex: 50,
          bubble: true, // 事件冒泡到地图上
          extData: {
            id: this.map.getAllOverlays('polygon').length,
            type: 'self'
          }
        })

        let pathLength = currentArea.getPath().length
        if (pathLength<3) {
          this._overDrawPolygon(true)
          setTimeout(()=>{
            this._drawPolygon()
          },10)
          return
        }

        if (this._isInRingRingIntersectFn(currentArea, '所绘制的区域间不可有交点...') || this._isRingInRingFn(currentArea, '所绘制的区域间不可有交点...')) {
          this._drawPolygon() // 开始绘画
          return
        }
           // 当前区域是否在当前区域组
        this.map.add(currentArea)
        this._polyEditor(currentArea)
        currentArea.on('click', (e)=>{
          if (this.isShowCurrentRang) return this.$message.error('当前不可编辑')
          this._polyEditor(currentArea)
          this._overDrawPolygon(true)
          setTimeout(()=>{
            this._drawPolygon()
          },10)
        })
        this._drawPolygon() // 开始绘画
      },

      _isInRingRingIntersectFn(currentArea, text){ // 当前区域是否在当前区域组
        let allPolygons = this.map.getAllOverlays('polygon')
        let isInRingRingIntersect = allPolygons.filter((l)=>{return l.getExtData().id !== currentArea.getExtData().id}).some((x)=>{
          return AMap.GeometryUtil.doesRingRingIntersect(currentArea.getPath(), x.getPath())
        })
        if (isInRingRingIntersect) {
          setTimeout(()=>{
            this._polyEditorClose()
          }, 0)
          this.map.remove([...this.map.getAllOverlays('marker').filter((x)=>x.getExtData().type !== 'storeCenter')])
          text && this.$message.error(text)
        }

        return isInRingRingIntersect
      },

      _isRingInRingFn(currentArea, text){ // '两圈关系：在大圈内
        let allPolygons = this.map.getAllOverlays('polygon')
        let isRingInRingBu = allPolygons.filter((l)=>{return l.getExtData().id !== currentArea.getExtData().id}).some((x)=>{
          return AMap.GeometryUtil.isRingInRing(currentArea.getPath(), x.getPath())
        })
        if (isRingInRingBu) {
          setTimeout(()=>{
            this._polyEditorClose()
          }, 0)
          this.map.remove([...this.map.getAllOverlays('marker').filter((x)=>x.getExtData().type !== 'storeCenter')])
          text && this.$message.error(text)
        }

        return isRingInRingBu
      },



      isStarDrawingHandle(){
        this.isStarDrawing = !this.isStarDrawing
        if (this.isStarDrawing) {
          this._drawPolygon()
        } else {
          this._overDrawPolygon(true)
        }
      },

      _drawPolygon() { // 绘制多变形
        this.isAddIng = true
        if (!this.isStarDrawing) return
        this.mouseTool.polygon({
          strokeColor: '#FF33FF',
          strokeWeight: 4,
          strokeOpacity: 0.2,
          fillColor: this.color,
          fillOpacity: 0.4,
          // 线样式还支持 'dashed'
          strokeStyle: 'solid'
          // strokeStyle是dashed时有效
          // strokeDasharray: [30,10],
        })
      },

      getPathArr: function (path) {
        var pathObj = [];
        path.forEach(function (item) {
          pathObj.push([item.lng, item.lat]);
        })
        return pathObj;
      },

      _overDrawPolygon(ifClear = false) { // 结束矢量绘制 ifClear:是否清楚当前绘制的图形
        this.mouseTool&&this.mouseTool.close(ifClear)
        this.isAddIng = false
      },

      _addDelMarker(position, polygon, id){ // 添加删除覆盖物
        let mark = new AMap.Marker({
          position,
          anchor: 'center',
          size: new AMap.Size(40, 40),
          icon: map_del_icon,
          offset: new AMap.Pixel(0, -30)
        });

        this.map.add(mark)

        mark.on('click', (e)=>{
          this._overDrawPolygon()
          this.$confirm({
            title: '提示',
            content: `确认删除该绘制区域吗？`,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
              this._polyEditorClose()
              setTimeout(()=>{
                this._drawPolygon()
              },100)
              let textMarker = this.map.getAllOverlays('text').filter(x=>x.getExtData().id == id)[0]
              let marks = []
              if (textMarker) {
                marks = [mark, polygon, textMarker]
              } else {
                marks = [mark, polygon]
              }


              this.map.remove(marks)
            },
            onCancel: () =>{
              setTimeout(()=>{
                this._drawPolygon()
              },100)
            }
          })
        })
      },

      _getTopLnglat (paths) { //  获取区域的中最高点坐标
        var lb = new AMap.LngLat(0, 0);
        paths.forEach(function (item) {
          if (item && item.lat && (item.lat > lb.lat)) {
            lb = item;
          }
        })
        return lb;
      },

      searchHandle(){ // 地图搜索
        this.placeSearch.search(this.keywords, (status, result)=>{
          console.log(result, '搜索出来的结果')
          if (status == 'complete') {
            this.searchList = result.poiList.pois
            this.isShowSearchList = true
          }
        })
      },

      serchItemClickHandle(e){ // 地图点击
        this.map.setCenter([e.location.lng, e.location.lat])
        this.isShowSearchList = false
      },



      /*地图相关e*/

      closeHandle(){ // 关闭
        this.callBack('cancel')
      },
      confirmHandle(){ // 确定
        let polygons = this.map.getAllOverlays('polygon').filter(x=>x.getExtData().type === 'self')
        let coordinatesArr = polygons.map((x1)=>{
            return x1.getPath().map(x2=>{
              return [x2.getLng(), x2.getLat()]
            })
        })
        this._setServiceScopeCoordinates(coordinatesArr)
      },
      _setServiceScopeCoordinates(coordinatesArr){ // 设置服务范围
        coordinatesArr = coordinatesArr.map((x1)=>{
          return  x1.map((x2)=>{
            return {
              "lng": x2[0],
              "lat": x2[1]
            }
          })
        })
        this.confirmLoading = true
        setServiceScopeCoordinates({id: this.id, coordinatesArr}).then((res)=>{
          this.$message.success('更新成功')

          this.callBack('ok')
        }).finally(()=>{ this.confirmLoading = false})
      },
    }
  }
</script>

<style scoped>
  .w-400{width: 400px}
  /deep/ .ant-modal-content{top: -50px}
  /deep/ .ant-btn-link:hover{color: red}
  .ss-serach-box{ box-shadow: 0 0px 10px 0 rgba(0,0,0,.05); max-height: 450px; overflow: auto; z-index: 10000}
</style>